package com.jichaoyun.service.impl;

import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jichaoyun.common.model.PagedResult;
import com.jichaoyun.common.utils.PoiExcelStyle;
import com.jichaoyun.dao.mapper.FlowHourMapper;
import com.jichaoyun.dao.mapper.RealdataMapper;
import com.jichaoyun.model.entity.FlowHour;
import com.jichaoyun.model.entity.Realdata;
import com.jichaoyun.model.entity.StationInfo;
import com.jichaoyun.common.enums.MyExceptiontType;
import com.jichaoyun.dao.mapper.StationInfoMapper;
import com.jichaoyun.service.IFlowHourService;
import com.jichaoyun.dao.mapper.FlowDayMapper;
import com.jichaoyun.service.IStationInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.File;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
* @author zhen
* @description 针对表【flow_hour】的数据库操作Service实现
* @createDate 2023-11-23 20:22:53
*/
@Service
public class FlowHourServiceImpl extends ServiceImpl<FlowHourMapper, FlowHour>
    implements IFlowHourService {
    @Resource
    private FlowHourMapper flowHourMapper;

    @Autowired
    private StationInfoMapper stationInfoMapper;

    @Autowired
    private IStationInfoService stationInfoService;

    @Autowired
    private RealdataMapper realdataMapper;

    /**
     * 导出用户日报表
     * @param response
     * @throws IOException
     */
    @Override
    public void getUserDayDataExcel(Integer station_no, String date,HttpServletResponse response) throws IOException {
        // 定义日期格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        // 将字符串转换为 LocalDate
        LocalDate theDate = LocalDate.parse(date, formatter);
        LocalDate lastYearDate = LocalDate.parse(date, formatter).minusYears(1);

        Map<String,Object> map1 = getStationDayForm(station_no,theDate);
        Map<String,Object> map2 = getStationDayForm(station_no,lastYearDate);

        List<Map<String,Object>> resList = new ArrayList<>();
        resList.add(map1);
        resList.add(map2);

        // 创建一个 ExcelWriter 把 list 数据用这个writer写出来(生成出来)
        ExcelWriter wr = ExcelUtil.getWriter( true);
        wr.write(resList, true);

        //设置excel的导出样式
        PoiExcelStyle.setStyleSet(wr,resList);

        // 创建 DateTimeFormatter 对象，定义日期格式
        DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("yyyy年M月d日 ");
        // 使用 DateTimeFormatter 格式化 LocalDateTime 对象
        String formattedDate = theDate.format(formatter1);

        // 把这个 excel 下载下来
        response.setContentType("application/vnd.gpenxmlfonmats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode(formattedDate+"单用户日报表", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader( "Content-Disposition", "attachment;filename="+fileName+".xlsx");
        ServletOutputStream out = response.getOutputStream();
        wr.flush(out,true);
        wr.close();
        IoUtil.close(System.out);
    }

    /**
     * 生成用户日报表到指定路径，而非直接响应请求
     * @param stationNo,date
     * @throws IOException
     * @return File
     */
    @Override
    public File generateDailyExcelFile(Integer stationNo, String date) throws IOException {
        // 定义日期格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        // 将字符串转换为 LocalDate
        LocalDate theDate = LocalDate.parse(date, formatter);
        LocalDate lastYearDate = LocalDate.parse(date, formatter).minusYears(1);

        Map<String, Object> mapToday = getStationDayForm(stationNo, theDate);
        Map<String, Object> mapYesterday = getStationDayForm(stationNo, lastYearDate);

        List<Map<String, Object>> resList = new ArrayList<>();
        resList.add(mapToday);
        resList.add(mapYesterday);

        // 创建一个 ExcelWriter 把 list 数据用这个 writer 写出来(生成出来)
        ExcelWriter wr = ExcelUtil.getWriter(true);
        wr.write(resList, true);

        // 设置 excel 的导出样式
        PoiExcelStyle.setStyleSet(wr, resList);
        // 创建 DateTimeFormatter 对象，定义日期格式
        DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("yyyy年M月d日 ");
        // 使用 DateTimeFormatter 格式化 LocalDateTime 对象
        String formattedDate = theDate.format(formatter1);

        // 创建临时文件
        File tempFile = File.createTempFile("daily_report_", ".xlsx");
        try (FileOutputStream fos = new FileOutputStream(tempFile)) {
            wr.flush(fos, true);
        } finally {
            wr.close();
        }
        return tempFile;
    }

    /**
     * 获取某日用户日报信息
     * @param station_no
     * @param date
     * @return
     */
    @Override
    public Map<String, Object> getStationDayForm(Integer station_no, LocalDate date) {
        Map<String, Object> map = new LinkedHashMap<>();

        // 获取当前日的第一分钟（00:00:00）
        LocalDateTime startOfDay = date.atStartOfDay();

        // 获取当前日期的最后一分钟（23:59:59）
        LocalDateTime endOfDay = date.atTime(LocalTime.MAX);

        LambdaQueryWrapper<FlowHour> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(FlowHour::getStation,station_no)
                .ge(FlowHour::getRecStart,startOfDay)
                .le(FlowHour::getRecStart,endOfDay)
                .orderByAsc(FlowHour::getId);

        List<FlowHour> flowHourList = flowHourMapper.selectList(wrapper);

        for (FlowHour flowHour : flowHourList) {
            if(flowHour.getFEnd()!=null){
                if (flowHour.getFStart() == null) flowHour.setFStart(0.0f);
                map.put(flowHour.getRecStart().getHour()+"时",flowHour.getFEnd()-flowHour.getFStart());
            }
        }
        return map;
    }

    /**
     * 根据传入的时间和日期查找小时数居
     * @param stationName
     * @param localDateTime
     * @return
     */
    @Override
    public Map<String, Object> getDataByTime(String stationName, LocalDateTime localDateTime) {

        //根据站点名称查找站号
        LambdaQueryWrapper<StationInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StationInfo::getStationName,stationName);
        Integer stationNo = this.stationInfoMapper.selectOne(wrapper).getStationNo();


        LocalDateTime start  = localDateTime;
        LocalDateTime end = localDateTime.plusSeconds(180);

        List<Realdata> historyDatas = realdataMapper.historySelect(stationNo, start, end);
        Map<String,Object> result = new HashMap<>();
        if(historyDatas.size()==0){
            result.put("流速",0);
            result.put("温度",0);
            result.put("压力",0);
            result.put("频率",0);
            result.put("总量",0);
            result.put("余额",0);
            return result;
        }
        Realdata historyData = historyDatas.get(0);
        result.put("流速",historyData.getFlow());
        result.put("温度",historyData.getTemp());
        result.put("压力",historyData.getPres());
        result.put("频率",historyData.getFreq());
        result.put("总量",historyData.getTotal());
        result.put("余额",historyData.getBalance());

        return result;
    }

    /**
     * 根据日期和站点名返回流速分析数据
     * @param stationName
     * @param localDate
     * @return
     */
    @Override
    public Map<String,Object> getFlowByDateTime(String stationName, LocalDate localDate) {

        //根据站点名称查找站号
        LambdaQueryWrapper<StationInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StationInfo::getStationName,stationName);
        Integer stationNo = this.stationInfoMapper.selectOne(wrapper).getStationNo();

        //根据站号和时间查找当日数据
        LambdaQueryWrapper<FlowHour> queryWrapper = new LambdaQueryWrapper<>();
        LocalDateTime day_start = LocalDateTime.of(localDate, LocalTime.MIN);
        LocalDateTime day_end = LocalDateTime.of(localDate, LocalTime.MAX);
        queryWrapper.eq(FlowHour::getStation,stationNo)
                .ge(FlowHour::getRecStart,day_start)
                .lt(FlowHour::getRecStart,day_end);
        List<FlowHour> flowHourList = this.flowHourMapper.selectList(queryWrapper);

        //根据站号和时间查找前日数据
        LambdaQueryWrapper<FlowHour> queryWrapper1 = new LambdaQueryWrapper<>();
        LocalDateTime day_before_start = LocalDateTime.of(localDate.minusDays(1), LocalTime.MIN);
        LocalDateTime day_before_end = LocalDateTime.of(localDate.minusDays(1), LocalTime.MAX);
        queryWrapper1.eq(FlowHour::getStation,stationNo)
                .ge(FlowHour::getRecStart,day_before_start)
                .lt(FlowHour::getRecStart,day_before_end);
        List<FlowHour> flowHourList1 = this.flowHourMapper.selectList(queryWrapper1);
        Map<String,Object> map = new HashMap<>();
        Float max = 0F,min = 3e38F;

        //遍历当日链表结果，找出最大和最小的流速
        LocalDateTime max_time = LocalDateTime.now() , min_time = LocalDateTime.now();
        for(FlowHour item : flowHourList){
            if(item.getFlowStart() == null) continue;
            if(item.getFlowStart() > max) {
                max = item.getFlowStart();
                max_time = item.getRecStart();
            }
            if(item.getFlowStart() < min) {
                min = item.getFlowStart();
                min_time = item.getRecStart();
            }
        }
        if(flowHourList.isEmpty()){
            max = null;
            min = null;
        }

        map.put("当日最高流速",max);
        map.put("当日最低流速",min);
        map.put("当日最高流速时间", String.valueOf(max_time));
        map.put("当日最低流速时间", String.valueOf(min_time));

        //遍历前日链表结果，找出最大和最小的流速
        Float max_before = 0F,min_before = 3e38F;
        LocalDateTime max_time_before = LocalDateTime.now() , min_time_before = LocalDateTime.now();
        for(FlowHour item : flowHourList1){
            if(item.getFlowStart() == null) continue;
            if(item.getFlowStart() > max_before) {
                max_before = item.getFlowStart();
                max_time_before = item.getRecStart();
            }
            if(item.getFlowStart() < min_before) {
                min_before = item.getFlowStart();
                min_time_before = item.getRecStart();
            }
        }
        if(flowHourList1.isEmpty()){
            max_before = null;
            min_before = null;
        }

        map.put("前日最高流速",max_before);
        map.put("前日最低流速",min_before);
        map.put("前日最高流速时间", String.valueOf(max_time_before));
        map.put("前日最低流速时间", String.valueOf(min_time_before));
        map.put("站名",stationName);
        map.put("站号",stationNo);

        return map;
    }

    /**
     * 根据日期和站点名返回温度分析数据
     * @param stationName
     * @param localDate
     * @return
     */
    @Override
    public Map<String,Object> getTempByDateTime(String stationName, LocalDate localDate) {

        //根据站点名称查找站号
        LambdaQueryWrapper<StationInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StationInfo::getStationName,stationName);
        Integer stationNo = this.stationInfoMapper.selectOne(wrapper).getStationNo();

        //根据站号和时间查找当日数据
        LambdaQueryWrapper<FlowHour> queryWrapper = new LambdaQueryWrapper<>();
        LocalDateTime day_start = LocalDateTime.of(localDate, LocalTime.MIN);
        LocalDateTime day_end = LocalDateTime.of(localDate, LocalTime.MAX);
        queryWrapper.eq(FlowHour::getStation,stationNo)
                .ge(FlowHour::getRecStart,day_start)
                .lt(FlowHour::getRecStart,day_end);
        List<FlowHour> flowHourList = this.flowHourMapper.selectList(queryWrapper);

        //根据站号和时间查找前日数据
        LambdaQueryWrapper<FlowHour> queryWrapper1 = new LambdaQueryWrapper<>();
        LocalDateTime day_before_start = LocalDateTime.of(localDate.minusDays(1), LocalTime.MIN);
        LocalDateTime day_before_end = LocalDateTime.of(localDate.minusDays(1), LocalTime.MAX);
        queryWrapper1.eq(FlowHour::getStation,stationNo)
                .ge(FlowHour::getRecStart,day_before_start)
                .lt(FlowHour::getRecStart,day_before_end);
        List<FlowHour> flowHourList1 = this.flowHourMapper.selectList(queryWrapper1);

        //遍历当日链表结果，找出最大和最小的温度
        Float max = 0F,min = 3e38F;
        LocalDateTime max_time = LocalDateTime.now() , min_time = LocalDateTime.now();
        for(FlowHour item : flowHourList){
            if(item.getTempStart() == null) continue;
            if(item.getTempStart() > max) {
                max = item.getTempStart();
                max_time = item.getRecStart();
            }
            if(item.getTempStart() < min) {
                min = item.getTempStart();
                min_time = item.getRecStart();
            }
        }

        Map<String,Object> map = new HashMap<>();


        if(flowHourList.isEmpty()){
            max = null;
            min = null;
        }
        map.put("当日最高温度",max);
        map.put("当日最低温度",min);
        map.put("当日最高温度时间", String.valueOf(max_time));
        map.put("当日最低温度时间", String.valueOf(min_time));

        //遍历前日链表结果，找出最高和最低的温度
        Float max_before = 0F,min_before = 3e38F;
        LocalDateTime max_time_before = LocalDateTime.now() , min_time_before = LocalDateTime.now();
        for(FlowHour item : flowHourList1){
            if(item.getTempStart() == null) continue;
            if(item.getTempStart() > max_before) {
                max_before = item.getTempStart();
                max_time_before = item.getRecStart();
            }
            if(item.getTempStart() < min_before) {
                min_before = item.getTempStart();
                min_time_before = item.getRecStart();
            }
        }

        if(flowHourList1.isEmpty()){
            max_before = null;
            min_before = null;
        }

        map.put("前日最高温度",max_before);
        map.put("前日最低温度",min_before);
        map.put("前日最高温度时间", String.valueOf(max_time_before));
        map.put("前日最低温度时间", String.valueOf(min_time_before));
        map.put("站名",stationName);
        map.put("站号",stationNo);

        return map;
    }

    /**
     * 根据日期和站点名返回压力分析数据
     * @param stationName
     * @param localDate
     * @return
     */
    @Override
    public Map<String,Object> getPresByDateTime(String stationName, LocalDate localDate) {

        //根据站点名称查找站号
        LambdaQueryWrapper<StationInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StationInfo::getStationName,stationName);
        Integer stationNo = this.stationInfoMapper.selectOne(wrapper).getStationNo();

        //根据站号和时间查找当日数据
        LambdaQueryWrapper<FlowHour> queryWrapper = new LambdaQueryWrapper<>();
        LocalDateTime day_start = LocalDateTime.of(localDate, LocalTime.MIN);
        LocalDateTime day_end = LocalDateTime.of(localDate, LocalTime.MAX);
        queryWrapper.eq(FlowHour::getStation,stationNo)
                .ge(FlowHour::getRecStart,day_start)
                .lt(FlowHour::getRecStart,day_end);
        List<FlowHour> flowHourList = this.flowHourMapper.selectList(queryWrapper);

        //根据站号和时间查找前日数据
        LambdaQueryWrapper<FlowHour> queryWrapper1 = new LambdaQueryWrapper<>();
        LocalDateTime day_before_start = LocalDateTime.of(localDate.minusDays(1), LocalTime.MIN);
        LocalDateTime day_before_end = LocalDateTime.of(localDate.minusDays(1), LocalTime.MAX);
        queryWrapper1.eq(FlowHour::getStation,stationNo)
                .ge(FlowHour::getRecStart,day_before_start)
                .lt(FlowHour::getRecStart,day_before_end);
        List<FlowHour> flowHourList1 = this.flowHourMapper.selectList(queryWrapper1);

        //遍历当日链表结果，找出最大和最小的压力
        Float max = 0F,min = 3e38F;
        LocalDateTime max_time = LocalDateTime.now() , min_time = LocalDateTime.now();
        for(FlowHour item : flowHourList){
            if(item.getPresStart() == null) continue;
            if(item.getPresStart() > max) {
                max = item.getPresStart();
                max_time = item.getRecStart();
            }
            if(item.getPresStart() < min) {
                min = item.getPresStart();
                min_time = item.getRecStart();
            }
        }

        Map<String,Object> map = new HashMap<>();

        if(flowHourList.isEmpty()){
            max = null;
            min = null;
        }
        map.put("当日最高压力",max);
        map.put("当日最低压力",min);
        map.put("当日最高压力时间", String.valueOf(max_time));
        map.put("当日最低压力时间", String.valueOf(min_time));

        //遍历前日链表结果，找出最高和最低的压力
        Float max_before = 0F,min_before = 3e38F;
        LocalDateTime max_time_before = LocalDateTime.now() , min_time_before = LocalDateTime.now();
        for(FlowHour item : flowHourList1){
            if(item.getPresStart() == null) continue;
            if(item.getPresStart() > max_before) {
                max_before = item.getPresStart();
                max_time_before = item.getRecStart();
            }
            if(item.getPresStart() < min_before) {
                min_before = item.getPresStart();
                min_time_before = item.getRecStart();
            }
        }
        if(flowHourList1.isEmpty()){
            max_before = null;
            min_before = null;
        }

        map.put("前日最高压力",max_before);
        map.put("前日最低压力",min_before);
        map.put("前日最高压力时间", String.valueOf(max_time_before));
        map.put("前日最低压力时间", String.valueOf(min_time_before));
        map.put("站名",stationName);
        map.put("站号",stationNo);

        return map;
    }

    /**
     * 根据日期分页获取当日所有流速分析
     * @param localDate
     * @param pageNo
     * @param pageSize
     * @return
     */
    @Override
    public PagedResult getAllFlowByDate(LocalDate localDate, Integer pageNo, Integer pageSize) {

        List<Map<String,Object>> resList = new ArrayList<>();

        PagedResult pagedResult = new PagedResult();
    //查找当日记录
        LocalDateTime day_start = LocalDateTime.of(localDate, LocalTime.MIN);
        LocalDateTime day_end = LocalDateTime.of(localDate, LocalTime.MAX);
        LocalDateTime day_before_start = LocalDateTime.of(localDate.minusDays(1), LocalTime.MIN);
        LocalDateTime day_before_end = LocalDateTime.of(localDate.minusDays(1), LocalTime.MAX);

        IPage<StationInfo> infoIPage = stationInfoService.getAllStationInfo(pageNo,pageSize);
        List<StationInfo> stationInfos = infoIPage.getRecords();
        pagedResult.setTotal((int) infoIPage.getTotal());
        pagedResult.setPages((int) infoIPage.getPages());

        for(StationInfo stationInfo:stationInfos){
            Map<String,Object> resMap = new LinkedHashMap<>();

            QueryWrapper<FlowHour> queryWrapper = new QueryWrapper<>();
            queryWrapper.select("rec_start","flow_start")
                    .ge("rec_start",day_start)
                    .lt("rec_start",day_end)
                    .eq("station",stationInfo.getStationNo())
                    .orderByDesc("flow_start");
            List<FlowHour> list_1 = this.flowHourMapper.selectList(queryWrapper);
            if(list_1.isEmpty()){
                resMap.put("站号",stationInfo.getStationNo());
                resMap.put("站名",stationInfo.getStationName());
                resMap.put("当日最高流速",0);
                resMap.put("当日最高流速时间",day_start.toString());
            }else{
                FlowHour today_max_result = list_1.get(0);

                resMap.put("站号",stationInfo.getStationNo());
                resMap.put("站名",stationInfo.getStationName());
                resMap.put("当日最高流速",today_max_result.getFlowStart());
                resMap.put("当日最高流速时间",today_max_result.getRecStart().toString());
            }


            QueryWrapper<FlowHour> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.ge("rec_start",day_start)
                    .lt("rec_start",day_end)
                    .eq("station",stationInfo.getStationNo())
                    .select("rec_start","flow_start")
                    .orderByAsc("flow_start");
            List<FlowHour> list_2 = this.flowHourMapper.selectList(queryWrapper1);
            if(list_2.isEmpty()){
                resMap.put("当日最低流速",0);
                resMap.put("当日最低流速时间",day_start.toString());
            }else{
                FlowHour today_min_result = list_2.get(0);

                resMap.put("当日最低流速",today_min_result.getFlowStart());
                resMap.put("当日最低流速时间",today_min_result.getRecStart().toString());
            }


//查找前日记录
            QueryWrapper<FlowHour> queryWrapper2 = new QueryWrapper<>();
            queryWrapper2.ge("rec_start",day_before_start)
                    .lt("rec_start",day_before_end)
                    .eq("station",stationInfo.getStationNo())
                    .select("rec_start","flow_start")
                    .orderByDesc("flow_start");
            List<FlowHour> list_3 = this.flowHourMapper.selectList(queryWrapper2);
            if(list_3.isEmpty()){
                resMap.put("前日最高流速",0);
                resMap.put("前日最高流速时间",day_before_start.toString());
            }else{
                FlowHour before_max_result = list_3.get(0);

                resMap.put("前日最高流速",before_max_result.getFlowStart());
                resMap.put("前日最高流速时间",before_max_result.getRecStart().toString());
            }


            QueryWrapper<FlowHour> queryWrapper3 = new QueryWrapper<>();
            queryWrapper3.ge("rec_start",day_before_start)
                    .lt("rec_start",day_before_end)
                    .eq("station",stationInfo.getStationNo())
                    .select("rec_start","flow_start")
                    .orderByAsc("flow_start");
            List<FlowHour> list_4 = this.flowHourMapper.selectList(queryWrapper3);
            if(list_4.isEmpty()){
                resMap.put("前日最低流速",0);
                resMap.put("前日最低流速时间",day_before_start.toString());
            }else{
                FlowHour before_min_result = list_4.get(0);

                resMap.put("前日最低流速",before_min_result.getFlowStart());
                resMap.put("前日最低流速时间",before_min_result.getRecStart().toString());
            }
            resList.add(resMap);
        }

        pagedResult.setRows(resList);

        return pagedResult;
    }

    @Override
    public List<Map<String, Object>> getAllFlowByDate(LocalDate localDate) {
        List<Map<String,Object>> resList = new ArrayList<>();

        LocalDateTime day_start = LocalDateTime.of(localDate, LocalTime.MIN);
        LocalDateTime day_end = LocalDateTime.of(localDate, LocalTime.MAX);
        LocalDateTime day_before_start = LocalDateTime.of(localDate.minusDays(1), LocalTime.MIN);
        LocalDateTime day_before_end = LocalDateTime.of(localDate.minusDays(1), LocalTime.MAX);

        LambdaQueryWrapper<StationInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.orderByAsc(StationInfo::getStationNo);
        List<StationInfo> stationInfoList = this.stationInfoMapper.selectList(lambdaQueryWrapper);

        for(StationInfo stationInfo:stationInfoList){
            Map<String,Object> resMap = new LinkedHashMap<>();

            QueryWrapper<FlowHour> queryWrapper = new QueryWrapper<>();
            queryWrapper.select("rec_start","flow_start")
                    .ge("rec_start",day_start)
                    .lt("rec_start",day_end)
                    .eq("station",stationInfo.getStationNo())
                    .orderByDesc("flow_start");
            List<FlowHour> list_1 = this.flowHourMapper.selectList(queryWrapper);
            if(list_1.isEmpty()){
                resMap.put("站号",stationInfo.getStationNo());
                resMap.put("站名",stationInfo.getStationName());
                resMap.put("当日最高流速",0);
                resMap.put("当日最高流速时间",day_start.toString());
            }else{
                FlowHour today_max_result = list_1.get(0);

                resMap.put("站号",stationInfo.getStationNo());
                resMap.put("站名",stationInfo.getStationName());
                resMap.put("当日最高流速",today_max_result.getFlowStart());
                resMap.put("当日最高流速时间",today_max_result.getRecStart().toString());
            }


            QueryWrapper<FlowHour> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.ge("rec_start",day_start)
                    .lt("rec_start",day_end)
                    .eq("station",stationInfo.getStationNo())
                    .select("rec_start","flow_start")
                    .orderByAsc("flow_start");
            List<FlowHour> list_2 = this.flowHourMapper.selectList(queryWrapper1);
            if(list_2.isEmpty()){
                resMap.put("当日最低流速",0);
                resMap.put("当日最低流速时间",day_start.toString());
            }else{
                FlowHour today_min_result = list_2.get(0);

                resMap.put("当日最低流速",today_min_result.getFlowStart());
                resMap.put("当日最低流速时间",today_min_result.getRecStart().toString());
            }


//查找前日记录
            QueryWrapper<FlowHour> queryWrapper2 = new QueryWrapper<>();
            queryWrapper2.ge("rec_start",day_before_start)
                    .lt("rec_start",day_before_end)
                    .eq("station",stationInfo.getStationNo())
                    .select("rec_start","flow_start")
                    .orderByDesc("flow_start");
            List<FlowHour> list_3 = this.flowHourMapper.selectList(queryWrapper2);
            if(list_3.isEmpty()){
                resMap.put("前日最高流速",0);
                resMap.put("前日最高流速时间",day_before_start.toString());
            }else{
                FlowHour before_max_result = list_3.get(0);

                resMap.put("前日最高流速",before_max_result.getFlowStart());
                resMap.put("前日最高流速时间",before_max_result.getRecStart().toString());
            }


            QueryWrapper<FlowHour> queryWrapper3 = new QueryWrapper<>();
            queryWrapper3.ge("rec_start",day_before_start)
                    .lt("rec_start",day_before_end)
                    .eq("station",stationInfo.getStationNo())
                    .select("rec_start","flow_start")
                    .orderByAsc("flow_start");
            List<FlowHour> list_4 = this.flowHourMapper.selectList(queryWrapper3);
            if(list_4.isEmpty()){
                resMap.put("前日最低流速",0);
                resMap.put("前日最低流速时间",day_before_start.toString());
            }else{
                FlowHour before_min_result = list_4.get(0);

                resMap.put("前日最低流速",before_min_result.getFlowStart());
                resMap.put("前日最低流速时间",before_min_result.getRecStart().toString());
            }
            resList.add(resMap);
        }

        return resList;
    }

    /**
     * 导出流量分析excel表
     * @param localDate
     * @param response
     * @throws IOException
     */
    @Override
    public void getAllFlowAnalyzeExcel(LocalDate localDate, HttpServletResponse response) throws IOException {
        List<Map<String,Object>> resList = getAllFlowByDate(localDate);

        // 创建一个 ExcelWriter 把 list 数据用这个writer写出来(生成出来)
        ExcelWriter wr = ExcelUtil.getWriter( true);
        wr.write(resList, true);

        //设置excel的导出样式
        PoiExcelStyle.setStyleSet(wr,resList);


        // 创建 DateTimeFormatter 对象，定义日期格式
        DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("yyyy年M月d日 ");
        // 使用 DateTimeFormatter 格式化 LocalDateTime 对象
        String formattedDate = localDate.format(formatter1);

        // 把这个 excel 下载下来
        response.setContentType("application/vnd.gpenxmlfonmats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode(formattedDate +"流量分析表", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader( "Content-Disposition", "attachment;filename="+fileName+".xlsx");
        ServletOutputStream out = response.getOutputStream();
        wr.flush(out,true);
        wr.close();
        IoUtil.close(System.out);
    }

    /**
     * 根据日期分页获取当日所有温度分析
     * @param localDate
     * @param pageNo
     * @param pageSize
     * @return
     */
    @Override
    public PagedResult getAllTempByDate(LocalDate localDate, Integer pageNo, Integer pageSize) {

        List<Map<String,Object>> resList = new ArrayList<>();

        PagedResult pagedResult = new PagedResult();
        //查找当日记录
        LocalDateTime day_start = LocalDateTime.of(localDate, LocalTime.MIN);
        LocalDateTime day_end = LocalDateTime.of(localDate, LocalTime.MAX);
        LocalDateTime day_before_start = LocalDateTime.of(localDate.minusDays(1), LocalTime.MIN);
        LocalDateTime day_before_end = LocalDateTime.of(localDate.minusDays(1), LocalTime.MAX);

        IPage<StationInfo> infoIPage = stationInfoService.getAllStationInfo(pageNo,pageSize);
        List<StationInfo> stationInfos = infoIPage.getRecords();
        pagedResult.setTotal((int) infoIPage.getTotal());
        pagedResult.setPages((int) infoIPage.getPages());

        for(StationInfo stationInfo:stationInfos){
            Map<String,Object> resMap = new LinkedHashMap<>();

            QueryWrapper<FlowHour> queryWrapper = new QueryWrapper<>();
            queryWrapper.select("rec_start","temp_start")
                    .ge("rec_start",day_start)
                    .lt("rec_start",day_end)
                    .eq("station",stationInfo.getStationNo())
                    .orderByDesc("temp_start");
            List<FlowHour> list_1 = this.flowHourMapper.selectList(queryWrapper);
            if(list_1.isEmpty()){
                resMap.put("站号",stationInfo.getStationNo());
                resMap.put("站名",stationInfo.getStationName());
                resMap.put("当日最高温度",0);
                resMap.put("当日最高温度时间",day_start.toString());
            }else{
                FlowHour today_max_result = list_1.get(0);

                resMap.put("站号",stationInfo.getStationNo());
                resMap.put("站名",stationInfo.getStationName());
                resMap.put("当日最高温度",today_max_result.getTempStart());
                resMap.put("当日最高温度时间",today_max_result.getRecStart().toString());
            }


            QueryWrapper<FlowHour> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.ge("rec_start",day_start)
                    .lt("rec_start",day_end)
                    .eq("station",stationInfo.getStationNo())
                    .select("rec_start","temp_start")
                    .orderByAsc("temp_start");
            List<FlowHour> list_2 = this.flowHourMapper.selectList(queryWrapper1);
            if(list_2.isEmpty()){
                resMap.put("当日最低温度",0);
                resMap.put("当日最低温度时间",day_start.toString());
            }else{
                FlowHour today_min_result = list_2.get(0);

                resMap.put("当日最低温度",today_min_result.getTempStart());
                resMap.put("当日最低温度时间",today_min_result.getRecStart().toString());
            }



//查找前日记录
            QueryWrapper<FlowHour> queryWrapper2 = new QueryWrapper<>();
            queryWrapper2.ge("rec_start",day_before_start)
                    .lt("rec_start",day_before_end)
                    .eq("station",stationInfo.getStationNo())
                    .select("rec_start","temp_start")
                    .orderByDesc("temp_start");
            List<FlowHour> list_3 = this.flowHourMapper.selectList(queryWrapper2);
            if(list_3.isEmpty()){
                resMap.put("前日最高温度",0);
                resMap.put("前日最高温度时间",day_before_start.toString());
            }else{
                FlowHour before_max_result = list_3.get(0);

                resMap.put("前日最高温度",before_max_result.getTempStart());
                resMap.put("前日最高温度时间",before_max_result.getRecStart().toString());
            }



            QueryWrapper<FlowHour> queryWrapper3 = new QueryWrapper<>();
            queryWrapper3.ge("rec_start",day_before_start)
                    .lt("rec_start",day_before_end)
                    .eq("station",stationInfo.getStationNo())
                    .select("rec_start","temp_start")
                    .orderByAsc("temp_start");
            List<FlowHour> list_4 = this.flowHourMapper.selectList(queryWrapper3);
            if(list_4.isEmpty()){
                resMap.put("前日最低温度",0);
                resMap.put("前日最低温度时间",day_before_start.toString());
            }else {
                FlowHour before_min_result = list_4.get(0);

                resMap.put("前日最低温度",before_min_result.getTempStart());
                resMap.put("前日最低温度时间",before_min_result.getRecStart().toString());
            }


            resList.add(resMap);
        }

        pagedResult.setRows(resList);

        return pagedResult;
    }

    @Override
    public List<Map<String, Object>> getAllTempByDate(LocalDate localDate) {
        List<Map<String,Object>> resList = new ArrayList<>();

        LocalDateTime day_start = LocalDateTime.of(localDate, LocalTime.MIN);
        LocalDateTime day_end = LocalDateTime.of(localDate, LocalTime.MAX);
        LocalDateTime day_before_start = LocalDateTime.of(localDate.minusDays(1), LocalTime.MIN);
        LocalDateTime day_before_end = LocalDateTime.of(localDate.minusDays(1), LocalTime.MAX);

        LambdaQueryWrapper<StationInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.orderByAsc(StationInfo::getStationNo);
        List<StationInfo> stationInfoList = this.stationInfoMapper.selectList(lambdaQueryWrapper);


        for(StationInfo stationInfo:stationInfoList){
            Map<String,Object> resMap = new LinkedHashMap<>();

            QueryWrapper<FlowHour> queryWrapper = new QueryWrapper<>();
            queryWrapper.select("rec_start","temp_start")
                    .ge("rec_start",day_start)
                    .lt("rec_start",day_end)
                    .eq("station",stationInfo.getStationNo())
                    .orderByDesc("temp_start");
            List<FlowHour> list_1 = this.flowHourMapper.selectList(queryWrapper);
            if(list_1.isEmpty()){
                resMap.put("站号",stationInfo.getStationNo());
                resMap.put("站名",stationInfo.getStationName());
                resMap.put("当日最高温度",0);
                resMap.put("当日最高温度时间",day_start.toString());
            }else{
                FlowHour today_max_result = list_1.get(0);

                resMap.put("站号",stationInfo.getStationNo());
                resMap.put("站名",stationInfo.getStationName());
                resMap.put("当日最高温度",today_max_result.getTempStart());
                resMap.put("当日最高温度时间",today_max_result.getRecStart().toString());
            }


            QueryWrapper<FlowHour> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.ge("rec_start",day_start)
                    .lt("rec_start",day_end)
                    .eq("station",stationInfo.getStationNo())
                    .select("rec_start","temp_start")
                    .orderByAsc("temp_start");
            List<FlowHour> list_2 = this.flowHourMapper.selectList(queryWrapper1);
            if(list_2.isEmpty()){
                resMap.put("当日最低温度",0);
                resMap.put("当日最低温度时间",day_start.toString());
            }else{
                FlowHour today_min_result = list_2.get(0);

                resMap.put("当日最低温度",today_min_result.getTempStart());
                resMap.put("当日最低温度时间",today_min_result.getRecStart().toString());
            }



//查找前日记录
            QueryWrapper<FlowHour> queryWrapper2 = new QueryWrapper<>();
            queryWrapper2.ge("rec_start",day_before_start)
                    .lt("rec_start",day_before_end)
                    .eq("station",stationInfo.getStationNo())
                    .select("rec_start","temp_start")
                    .orderByDesc("temp_start");
            List<FlowHour> list_3 = this.flowHourMapper.selectList(queryWrapper2);
            if(list_3.isEmpty()){
                resMap.put("前日最高温度",0);
                resMap.put("前日最高温度时间",day_before_start.toString());
            }else{
                FlowHour before_max_result = list_3.get(0);

                resMap.put("前日最高温度",before_max_result.getTempStart());
                resMap.put("前日最高温度时间",before_max_result.getRecStart().toString());
            }



            QueryWrapper<FlowHour> queryWrapper3 = new QueryWrapper<>();
            queryWrapper3.ge("rec_start",day_before_start)
                    .lt("rec_start",day_before_end)
                    .eq("station",stationInfo.getStationNo())
                    .select("rec_start","temp_start")
                    .orderByAsc("temp_start");
            List<FlowHour> list_4 = this.flowHourMapper.selectList(queryWrapper3);
            if(list_4.isEmpty()){
                resMap.put("前日最低温度",0);
                resMap.put("前日最低温度时间",day_before_start.toString());
            }else {
                FlowHour before_min_result = list_4.get(0);

                resMap.put("前日最低温度",before_min_result.getTempStart());
                resMap.put("前日最低温度时间",before_min_result.getRecStart().toString());
            }


            resList.add(resMap);
        }
        return resList;
    }

    /**
     * 导出温度分析表excel
     * @param localDate
     * @param response
     * @throws IOException
     */
    @Override
    public void getAllTempAnalyzeExcel(LocalDate localDate, HttpServletResponse response) throws IOException {
        List<Map<String,Object>> resList = getAllTempByDate(localDate);

        // 创建一个 ExcelWriter 把 list 数据用这个writer写出来(生成出来)
        ExcelWriter wr = ExcelUtil.getWriter( true);
        wr.write(resList, true);

        //设置excel的导出样式
        PoiExcelStyle.setStyleSet(wr,resList);


        // 创建 DateTimeFormatter 对象，定义日期格式
        DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("yyyy年M月d日 ");
        // 使用 DateTimeFormatter 格式化 LocalDateTime 对象
        String formattedDate = localDate.format(formatter1);

        // 把这个 excel 下载下来
        response.setContentType("application/vnd.gpenxmlfonmats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode(formattedDate +"温度分析表", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader( "Content-Disposition", "attachment;filename="+fileName+".xlsx");
        ServletOutputStream out = response.getOutputStream();
        wr.flush(out,true);
        wr.close();
        IoUtil.close(System.out);
    }

    /**
     * 根据日期分页获取当日所有压力分析
     * @param localDate
     * @param pageNo
     * @param pageSize
     * @return
     */
    @Override
    public PagedResult getAllPresByDate(LocalDate localDate, Integer pageNo, Integer pageSize) {

        List<Map<String,Object>> resList = new ArrayList<>();

        PagedResult pagedResult = new PagedResult();
        //查找当日记录
        LocalDateTime day_start = LocalDateTime.of(localDate, LocalTime.MIN);
        LocalDateTime day_end = LocalDateTime.of(localDate, LocalTime.MAX);
        LocalDateTime day_before_start = LocalDateTime.of(localDate.minusDays(1), LocalTime.MIN);
        LocalDateTime day_before_end = LocalDateTime.of(localDate.minusDays(1), LocalTime.MAX);

        IPage<StationInfo> infoIPage = stationInfoService.getAllStationInfo(pageNo,pageSize);
        List<StationInfo> stationInfos = infoIPage.getRecords();
        pagedResult.setTotal((int) infoIPage.getTotal());
        pagedResult.setPages((int) infoIPage.getPages());

        for(StationInfo stationInfo:stationInfos){
            Map<String,Object> resMap = new LinkedHashMap<>();

            QueryWrapper<FlowHour> queryWrapper = new QueryWrapper<>();
            queryWrapper.select("rec_start","pres_start")
                    .ge("rec_start",day_start)
                    .lt("rec_start",day_end)
                    .eq("station",stationInfo.getStationNo())
                    .orderByDesc("pres_start");
            List<FlowHour> list_1 = this.flowHourMapper.selectList(queryWrapper);
            if(list_1.isEmpty()){
                resMap.put("站号",stationInfo.getStationNo());
                resMap.put("站名",stationInfo.getStationName());
                resMap.put("当日最高压力",0);
                resMap.put("当日最高压力时间",day_start.toString());
            }else{
                FlowHour today_max_result = list_1.get(0);

                resMap.put("站号",stationInfo.getStationNo());
                resMap.put("站名",stationInfo.getStationName());
                resMap.put("当日最高压力",today_max_result.getPresStart());
                resMap.put("当日最高压力时间",today_max_result.getRecStart().toString());
            }


            QueryWrapper<FlowHour> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.ge("rec_start",day_start)
                    .lt("rec_start",day_end)
                    .eq("station",stationInfo.getStationNo())
                    .select("rec_start","pres_start")
                    .orderByAsc("pres_start");
            List<FlowHour> list_2 = this.flowHourMapper.selectList(queryWrapper1);
            if(list_2.isEmpty()){
                resMap.put("当日最低压力",0);
                resMap.put("当日最低压力时间",day_start.toString());
            }else{
                FlowHour today_min_result =list_2.get(0);

                resMap.put("当日最低压力",today_min_result.getPresStart());
                resMap.put("当日最低压力时间",today_min_result.getRecStart().toString());
            }


//查找前日记录
            QueryWrapper<FlowHour> queryWrapper2 = new QueryWrapper<>();
            queryWrapper2.ge("rec_start",day_before_start)
                    .lt("rec_start",day_before_end)
                    .eq("station",stationInfo.getStationNo())
                    .select("rec_start","pres_start")
                    .orderByDesc("pres_start");
            List<FlowHour> list_3 = this.flowHourMapper.selectList(queryWrapper2);
            if(list_3.isEmpty()){
                resMap.put("前日最高压力",0);
                resMap.put("前日最高压力时间",day_before_start.toString());
            }else {
                FlowHour before_max_result = list_3.get(0);

                resMap.put("前日最高压力",before_max_result.getPresStart());
                resMap.put("前日最高压力时间",before_max_result.getRecStart().toString());
            }



            QueryWrapper<FlowHour> queryWrapper3 = new QueryWrapper<>();
            queryWrapper3.ge("rec_start",day_before_start)
                    .lt("rec_start",day_before_end)
                    .eq("station",stationInfo.getStationNo())
                    .select("rec_start","pres_start")
                    .orderByAsc("pres_start");
            List<FlowHour> list_4 =  this.flowHourMapper.selectList(queryWrapper3);
            if(list_4.isEmpty()){
                resMap.put("前日最低压力",0);
                resMap.put("前日最低压力时间",day_before_start.toString());
            }else{
                FlowHour before_min_result =list_4.get(0);

                resMap.put("前日最低压力",before_min_result.getPresStart());
                resMap.put("前日最低压力时间",before_min_result.getRecStart().toString());
            }


            resList.add(resMap);
        }

        pagedResult.setRows(resList);

        return pagedResult;
    }

    @Override
    public List<Map<String, Object>> getAllPresByDate(LocalDate localDate) {
        List<Map<String,Object>> resList = new ArrayList<>();

        LocalDateTime day_start = LocalDateTime.of(localDate, LocalTime.MIN);
        LocalDateTime day_end = LocalDateTime.of(localDate, LocalTime.MAX);
        LocalDateTime day_before_start = LocalDateTime.of(localDate.minusDays(1), LocalTime.MIN);
        LocalDateTime day_before_end = LocalDateTime.of(localDate.minusDays(1), LocalTime.MAX);

        LambdaQueryWrapper<StationInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.orderByAsc(StationInfo::getStationNo);
        List<StationInfo> stationInfoList = this.stationInfoMapper.selectList(lambdaQueryWrapper);

        for(StationInfo stationInfo:stationInfoList){
            Map<String,Object> resMap = new LinkedHashMap<>();

            QueryWrapper<FlowHour> queryWrapper = new QueryWrapper<>();
            queryWrapper.select("rec_start","pres_start")
                    .ge("rec_start",day_start)
                    .lt("rec_start",day_end)
                    .eq("station",stationInfo.getStationNo())
                    .orderByDesc("pres_start");
            List<FlowHour> list_1 = this.flowHourMapper.selectList(queryWrapper);
            if(list_1.isEmpty()){
                resMap.put("站号",stationInfo.getStationNo());
                resMap.put("站名",stationInfo.getStationName());
                resMap.put("当日最高压力",0);
                resMap.put("当日最高压力时间",day_start.toString());
            }else{
                FlowHour today_max_result = list_1.get(0);

                resMap.put("站号",stationInfo.getStationNo());
                resMap.put("站名",stationInfo.getStationName());
                resMap.put("当日最高压力",today_max_result.getPresStart());
                resMap.put("当日最高压力时间",today_max_result.getRecStart().toString());
            }


            QueryWrapper<FlowHour> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.ge("rec_start",day_start)
                    .lt("rec_start",day_end)
                    .eq("station",stationInfo.getStationNo())
                    .select("rec_start","pres_start")
                    .orderByAsc("pres_start");
            List<FlowHour> list_2 = this.flowHourMapper.selectList(queryWrapper1);
            if(list_2.isEmpty()){
                resMap.put("当日最低压力",0);
                resMap.put("当日最低压力时间",day_start.toString());
            }else{
                FlowHour today_min_result =list_2.get(0);

                resMap.put("当日最低压力",today_min_result.getPresStart());
                resMap.put("当日最低压力时间",today_min_result.getRecStart().toString());
            }


//查找前日记录
            QueryWrapper<FlowHour> queryWrapper2 = new QueryWrapper<>();
            queryWrapper2.ge("rec_start",day_before_start)
                    .lt("rec_start",day_before_end)
                    .eq("station",stationInfo.getStationNo())
                    .select("rec_start","pres_start")
                    .orderByDesc("pres_start");
            List<FlowHour> list_3 = this.flowHourMapper.selectList(queryWrapper2);
            if(list_3.isEmpty()){
                resMap.put("前日最高压力",0);
                resMap.put("前日最高压力时间",day_before_start.toString());
            }else {
                FlowHour before_max_result = list_3.get(0);

                resMap.put("前日最高压力",before_max_result.getPresStart());
                resMap.put("前日最高压力时间",before_max_result.getRecStart().toString());
            }



            QueryWrapper<FlowHour> queryWrapper3 = new QueryWrapper<>();
            queryWrapper3.ge("rec_start",day_before_start)
                    .lt("rec_start",day_before_end)
                    .eq("station",stationInfo.getStationNo())
                    .select("rec_start","pres_start")
                    .orderByAsc("pres_start");
            List<FlowHour> list_4 =  this.flowHourMapper.selectList(queryWrapper3);
            if(list_4.isEmpty()){
                resMap.put("前日最低压力",0);
                resMap.put("前日最低压力时间",day_before_start.toString());
            }else{
                FlowHour before_min_result =list_4.get(0);

                resMap.put("前日最低压力",before_min_result.getPresStart());
                resMap.put("前日最低压力时间",before_min_result.getRecStart().toString());
            }


            resList.add(resMap);
        }
        return resList;
    }

    /**
     * 导出压力分析excel表
     * @param localDate
     * @param response
     * @throws IOException
     */
    @Override
    public void getAllPresAnalyzeExcel(LocalDate localDate, HttpServletResponse response) throws IOException {
        List<Map<String,Object>> resList = getAllPresByDate(localDate);

        // 创建一个 ExcelWriter 把 list 数据用这个writer写出来(生成出来)
        ExcelWriter wr = ExcelUtil.getWriter( true);
        wr.write(resList, true);

        //设置excel的导出样式
        PoiExcelStyle.setStyleSet(wr,resList);


        // 创建 DateTimeFormatter 对象，定义日期格式
        DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("yyyy年M月d日 ");
        // 使用 DateTimeFormatter 格式化 LocalDateTime 对象
        String formattedDate = localDate.format(formatter1);

        // 把这个 excel 下载下来
        response.setContentType("application/vnd.gpenxmlfonmats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode(formattedDate +"压力分析表", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader( "Content-Disposition", "attachment;filename="+fileName+".xlsx");
        ServletOutputStream out = response.getOutputStream();
        wr.flush(out,true);
        wr.close();
        IoUtil.close(System.out);
    }
}




